package com.szbmyoubao.app

import android.app.Application
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkCapabilities
import android.os.Build
import com.szbmyoubao.app.constant.BusConstants
import com.szbmyoubao.app.constant.Constants
import com.szbmyoubao.app.exception.GlobalExceptionHandler
import com.szbmyoubao.app.http.ServerConfig
import com.szbmyoubao.app.storage.AppStorage
import com.szbmyoubao.app.storage.UserStorage
import com.szbmyoubao.app.ui.login.LoginActivity
import com.szbmyoubao.app.utils.LogUtils
import com.ellecity06.common.helper.LoginHelper
import com.ellecity06.common.utils.netAvailable
import com.ellecity06.cwhiskymall.BuildConfig
import com.hjq.toast.Toaster
import com.jeremyliao.liveeventbus.LiveEventBus
import com.scwang.smart.refresh.header.ClassicsHeader
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.tencent.bugly.crashreport.CrashReport
import com.tencent.mmkv.MMKV
import com.tencent.smtt.sdk.QbSdk

/**
 * @author ellecity06
 * @time 2023/3/29 16:27
 * @des
 */
//@HiltAndroidApp
class App : Application() {
    override fun onCreate() {
        super.onCreate()
        appContext = this
        LoginHelper.instance.initialize(LoginActivity::class.java, ::onLogout)
        DebugManager.Companion.initSdk(this)

        if (AppStorage.Companion.agreement) {
            initSdk()
            initService()
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                connectivityManager?.registerDefaultNetworkCallback(networkCallback)
            }
            initJPush()
        }

    }

    private fun initService() {
        if (!BuildConfig.SERVER_RELEASE) {
            if (AppStorage.Companion.serviceConfig != null) {
                ServerConfig.Companion.baseHost = AppStorage.Companion.serviceConfig!!.apiUrl
                ServerConfig.Companion.baseH5Host = AppStorage.Companion.serviceConfig!!.webUrl
            }
        }
    }

    /**
     * 退出登录时候清除所有信息
     */
    private fun onLogout() {
        AppStorage.Companion.token = ""
        UserStorage.Companion.user = null
    }

    companion object {
        private const val TAG: String = "ApplicationLog"
        lateinit var appContext: App
    }

    fun initSdk() {
        // mmkv
        MMKV.initialize(this)
        Toaster.init(this)
        Thread.setDefaultUncaughtExceptionHandler(GlobalExceptionHandler(this))
        Runnable {
            //腾讯x5
            QbSdk.unForceSysWebView()
            QbSdk.initX5Environment(this, object : QbSdk.PreInitCallback {
                override fun onCoreInitFinished() {
                    LogUtils.e(TAG, "onCoreInitFinished")
                }

                override fun onViewInitFinished(b: Boolean) {
                    LogUtils.e(TAG, "onViewInitFinished")

                }
            })
            QbSdk.setDownloadWithoutWifi(true)

        }
        // 这里实现SDK初始化，appId替换成你的在Bugly平台申请的appId,调试时将第三个参数设置为true
        CrashReport.initCrashReport(this, Constants.Companion.BUGLY_ID, BuildConfig.DEBUG)
        initBuglyData()

    }

    private fun initJPush() {
//        JCollectionAuth.setAuth(this, true)
//        JPushInterface.setDebugMode(!BuildConfig.SERVER_RELEASE)
//        JPushInterface.init(this)
//        JPushHelper.setJPushAlias()
//        JPushInterface.getRegistrationID()
    }

    private fun initBuglyData() {
        if (AppStorage.Companion.token != null && AppStorage.Companion.token!!.isNotEmpty()) {
            CrashReport.setUserId(this, UserStorage.Companion.user?.phone ?: "")
            CrashReport.setUserSceneTag(this, UserStorage.Companion.user?.uid ?: 0)
            CrashReport.putUserData(this, "token", AppStorage.Companion.token)
        }

    }

    init {
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator { context, layout ->
            ClassicsHeader(context)
        }

    }

    private val connectivityManager: ConnectivityManager? by lazy {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getSystemService(ConnectivityManager::class.java)
        } else {
            null
        }
    }
    private val networkCallback = object : ConnectivityManager.NetworkCallback() {

        override fun onAvailable(network: Network) {
            // 网络连接了
            // 可以在这里检查网络是否可以访问互联网
            val networkCapabilities = connectivityManager?.getNetworkCapabilities(network)
            if (networkCapabilities?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) == true) {
                // 网络可以访问互联网
                if (!netAvailable){
                    netAvailable = true
                    LiveEventBus.get<Boolean>(BusConstants.Companion.NET_EVENT).post(netAvailable)
                }

            } else {
                // 网络已连接，但无法访问互联网
                netAvailable = false
            }

        }

        override fun onLost(network: Network) {
            // 网络连接丢失
            netAvailable = false
        }

    }
}


